import { ElMessage, ElLoading } from 'element-plus';
// let baseUrl = 'http://sandhead.aicaichina.com/api/';
let baseUrl = import.meta.env.VITE_APP_API;
// let baseUrl = 'http://192.168.110.58:9110/api/';

export default function request(
  method,
  url,
  body = undefined,
  formData = undefined,
  headers = {},
) {
  method = method.toUpperCase();
  if (method === 'GET') {
    // fetch的GET不允许有body，参数只能放在url中
    body = undefined;
  } else if (formData) {
    body = formData;
  } else {
    body = body && JSON.stringify(body);
  }

  let cookie = undefined;
  chrome.storage.local.get(['cookies'], function (res) {
    if (res['cookies']) {
      cookie = res['cookies'];
    }
  });

  headers.Cookie = cookie;

  const loadingInstance = ElLoading.service({
    lock: true,
    text: '请求中...',
    spinner: 'el-icon-loading',
  });

  return fetch(baseUrl + url, {
    method,
    headers,
    body,
  }).then(async (response) => {
    loadingInstance.close();
    let res = await response.json();
    if (!res.success) {
      ElMessage.error(res.message || 'error!');
    }
    return res;
  });
}
